package com.InsideGamer.SuperJailBreak;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;

import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.event.Event;
import org.bukkit.event.Event.Priority;
import org.bukkit.event.Event.Type;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;

public class JailBreak extends JavaPlugin
{
	public Logger log = Logger.getLogger("Minecraft");
	public PluginManager pm = getServer().getPluginManager();
	
	public AdminFunctions adminFunctions;
	public UserFunctions userFunctions;
	public YamlConfiguration configuration    = new YamlConfiguration ( );
	public YamlConfiguration usersConfig      = new YamlConfiguration ( );
	//public ProtectionClass protectionclass    = new ProtectionClass   ( this, "plugins/SuperJailBreak/protections.yml" );
	//public Protection protection = null;
	public Users users = null;
	
	// Init listeners.
	public BasicPlayerListener playerListener = new BasicPlayerListener ( this );
	public BasicBlockListener  blockListener  = new BasicBlockListener  ( this );
	
	@Override
	public void onDisable()
	{
		try {
			users.save();
			//protection.save();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		log.info ( "[SuperJailBreak] Plugin has been disabled ....");
	}

	@Override
	public void onEnable()
	{
		// Init
		//protectionclass.LoadAllProtection ( );
		
		adminFunctions = new AdminFunctions ( this );
		userFunctions = new UserFunctions ( this );
		
		try {
			configuration.load ( loadFile ( "config.yml" ) );
			usersConfig.load ( loadFile ( "users.yml" ) );
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InvalidConfigurationException e) {
			e.printStackTrace();
		}
		
		users      = new Users ( this, usersConfig, configuration );
		
		// Register player events.
		RegPlayerEvent ( Type.PLAYER_JOIN          );
		RegPlayerEvent ( Type.PLAYER_MOVE          );
		RegPlayerEvent ( Type.PLAYER_PICKUP_ITEM   );
		RegPlayerEvent ( Type.PLAYER_CHAT          );
		RegPlayerEvent ( Type.PLAYER_CHANGED_WORLD );
		RegPlayerEvent ( Type.PLAYER_INTERACT      );
		RegPlayerEvent ( Type.PLAYER_TELEPORT      );
		
		// Register block events.
		RegBlockEvent ( Type.BLOCK_BREAK );
		RegBlockEvent ( Type.BLOCK_PLACE );
		
		// Register server events.
		// TODO: Add server listener.
		
		// UserCommands
		UserCommands usercommands = new UserCommands ( this );
		getCommand ( "hire"    ).setExecutor ( usercommands );
		//getCommand ( "pay"     ).setExecutor ( usercommands );
		
		// AdminCommands
		AdminCommands admincommands = new AdminCommands ( this );
		getCommand ( "iclear" ).setExecutor ( admincommands );
		getCommand ( "hide"   ).setExecutor ( admincommands );
		//getCommand ( "protect").setExecutor ( admincommands );
		getCommand ( "join"   ).setExecutor ( admincommands );
		getCommand ( "kill"   ).setExecutor ( admincommands );
		getCommand ( "kick"   ).setExecutor ( admincommands );
		getCommand ( "ban"    ).setExecutor ( admincommands );
		getCommand ( "stop"   ).setExecutor ( admincommands );
		//getCommand ( "jailbreak" ).setExecutor(admincommands);
	}
	
	private void RegPlayerEvent ( Event.Type type )
	{
		RegPlayerEvent ( type, Priority.Normal );
	}
	
	private void RegPlayerEvent ( Event.Type type, Priority pr )
	{
		pm.registerEvent ( type, playerListener, pr, this );
	}
	
	private void RegBlockEvent ( Event.Type type )
	{
		RegBlockEvent ( type, Priority.Normal );
	}
	
	private void RegBlockEvent ( Event.Type type, Priority pr )
	{
		pm.registerEvent ( type, blockListener, pr, this );
	}
	
	private File loadFile ( String fileName )
	{
		// Check plugin directory existance
		try
		{
			File BasicDirectory = new File("plugins/SuperJailBreak/");
			if(!BasicDirectory.exists())
			{
				// Create dir
				BasicDirectory.mkdir();
				log.info ( "[SuperJailBreak] Created the SuperJailBreak plugin directory" );
			}
			
			// Attempt to load the "SuperJailBreak.yml" file
			File config = new File("plugins/SuperJailBreak/" + fileName);
			
			if(!config.exists())
			{
				// Copy over SuperJailBreak.yml
				InputStream defaultFile = getClass().getClassLoader().getResourceAsStream(fileName);
				// Create file...
				try
				{
					// Print out we are creating a new config file...
					log.info ( "[SuperJailBreak] Did not detect a config file: created new file \"" + fileName + "\"" );
					// Actually copy over as needed
					BufferedWriter out = new BufferedWriter(new FileWriter("plugins/SuperJailBreak/" + fileName));
					while(defaultFile.available() > 0)
						out.write(defaultFile.read());
					out.close();
				}
				catch(Exception e)
				{
					// Just fail out writing the error message
					log.info ( "[SuperJailBreak] Warning: " + e.getMessage() );
				}
				// Now re-open the file
				config = new File("plugins/SuperJailBreak/" + fileName);
			}
			
			// Return the file
			return config;
		}
		catch ( Exception e )
		{
			// Do something.
			return null;
		}
	}
	
	public void BroadcastMessage ( String message )
	{
		this.getServer().broadcastMessage ( message );
	}
}
